package com.wyh.domain.vo.groupOne.utils.TreeUtils;

import com.wyh.domain.dto.gfive.LoginUser;
import com.wyh.domain.vo.groupOne.utils.MasterDataDepartmentTree;
import com.wyh.domain.vo.groupOne.utils.MasterDataTreeNode;
import com.wyh.service.groupOne.threemeterAbout.threemeterTree.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MasterDataDepartmentTreeUtils {

    private final MasterDataIOrganizationVOService masterDataIOrganizationVOService;
    private final MasterDataIProjectVOService masterDataIProjectVOService;
    private final MasterDataIBuildingUnitsVOService masterDataIBuildingUnitsVOService;
    private final MasterDataILayerVOService masterDataILayerVOService;
    private final MasterDataIRoomVOService masterDataIRoomVOService;
    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public MasterDataDepartmentTreeUtils(
            MasterDataIOrganizationVOService masterDataIOrganizationVOService,
            MasterDataIProjectVOService masterDataIProjectVOService,
            MasterDataIBuildingUnitsVOService masterDataIBuildingUnitsVOService,
            MasterDataILayerVOService masterDataILayerVOService,
            MasterDataIRoomVOService masterDataIRoomVOService,
            RedisTemplate<String, Object> redisTemplate
    ) {
        this.masterDataIOrganizationVOService = masterDataIOrganizationVOService;
        this.masterDataIProjectVOService = masterDataIProjectVOService;
        this.masterDataIBuildingUnitsVOService = masterDataIBuildingUnitsVOService;
        this.masterDataILayerVOService = masterDataILayerVOService;
        this.masterDataIRoomVOService = masterDataIRoomVOService;
        this.redisTemplate = redisTemplate;
    }

    // 更新部门树结构，并更新版本号
    public void updateDepartmentTree(Integer userId) {
        // 获取当前版本号
        String versionKey = "wyh:MasterDataDepartmentTree:globalVersion";
        Long currentVersion = (Long) redisTemplate.opsForValue().get(versionKey);

        // 增加版本号
        long newVersion = (currentVersion != null ? currentVersion + 1 : 1);

        // 构建新的树并存入 Redis
        buildDepartmentTree(userId, newVersion);

        // 更新 Redis 中的版本号
        redisTemplate.opsForValue().set(versionKey, newVersion);
    }

    // 从数据库中获取部门树结构的逻辑
    public List<MasterDataTreeNode> fetchTreeFromDatabase() {
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Integer organizationid = loginUser.getUser().getOrganizationid();
        Integer userid = loginUser.getUser().getId();
        String account = loginUser.getUser().getAccount();
        return MasterDataDepartmentTree.buildUserDepartmentTree(userid, organizationid,
                masterDataIOrganizationVOService.findAll(),
                masterDataIProjectVOService.findAllByConnected(account),
                masterDataIBuildingUnitsVOService.findAll(),
                masterDataILayerVOService.findAll(),
                masterDataIRoomVOService.findAll());
    }

    // 从数据库中重建树并存入 Redis
    public MasterDataDepartmentTreewithVersion buildDepartmentTree(Integer userId, long newVersion) {
        List<MasterDataTreeNode> masterDataTreeNodes = fetchTreeFromDatabase();
        MasterDataDepartmentTreewithVersion masterDataDepartmentTreewithVersion = new MasterDataDepartmentTreewithVersion();
        masterDataDepartmentTreewithVersion.setVersion(newVersion);
        masterDataDepartmentTreewithVersion.setTreeNodes(masterDataTreeNodes);
        // 更新 Redis 中的树
        String redisKey = "wyh:MasterDataDepartmentTree:" + userId;
        redisTemplate.opsForValue().set(redisKey, masterDataDepartmentTreewithVersion);
        return masterDataDepartmentTreewithVersion;
    }

    // 获取部门树结构，检查版本号
    public MasterDataDepartmentTreewithVersion getDepartmentTree(Integer userId) {
        long currentVersion = getCurrentVersionFromRedis();
        MasterDataDepartmentTreewithVersion treeFromRedis = getTreeFromRedis(userId);
        if (treeFromRedis != null && treeFromRedis.getVersion() == currentVersion) {
            return treeFromRedis;
        } else {
            return buildDepartmentTree(userId, currentVersion);
        }
    }

    private MasterDataDepartmentTreewithVersion getTreeFromRedis(Integer userId) {
        String redisKey = "wyh:MasterDataDepartmentTree:" + userId;
        return (MasterDataDepartmentTreewithVersion) redisTemplate.opsForValue().get(redisKey);
    }

    private long getCurrentVersionFromRedis() {
        Long currentVersion = (Long) redisTemplate.opsForValue().get("wyh:MasterDataDepartmentTree:globalVersion");
        return (currentVersion != null) ? currentVersion : 0;
    }
}
